const Cart = require('../model/cart.model')
const {Op} = require('sequelize')
const Goods = require('../model/goods.model')
class cartService{

    async creatOrUpdate({goods_id,user_id}){
        //根据user_id和goods_id同时查找，有没有记录
        const res = await Cart.findOne({
            where:{
                [Op.and]:{
                    user_id,
                    goods_id
                }
            }
        })

        if(res){
            //存在这条数据
            await res.increment('number')
            return await res.reload()
        }else{
            return await Cart.create({goods_id,user_id})
             
        }
    }

    async findCarts({pageNum,pageSize}){
        try {
            
            const offset  = (pageNum-1)*pageSize
    
            const {count,rows}  = await Cart.findAndCountAll({
                offset:offset,
                limit:pageSize *1,
                attributes:['id','number','selected'],
                include: {
                    model:Goods,
                    as:'goods_info',
                    attributes:['id','goods_name','goods_price','goods_img'],
                }
            })
    
            return{
                pageNum,
                pageSize,
                total:count,
                list:rows
            }
        } catch (error) {
            console.log(error);
        }
        
    }

    async updateCarts(params){
        const {id,number,selected} = params
        const res = await Cart.findByPk(id)
        if(!res) return ''
        number!==undefined ? (res.number = number) : ''
        if(selected!==undefined) {
            res.selected = selected
        }
        return await res.save()
        
    }
    async removeCarts(ids){
        try {
            return await Cart.destroy({
                where:{
                    id:{
                        [Op.in]:ids
                    }
                }
    
            })
        } catch (error) {
            console.log(error);
            
        }
    }
    async selectedAllCarts({user_id,selecteId}){
        // const a = true
        // selecteId=1? (a=true) : (a=false)
        console.log(selecteId);
        
        return await Cart.update({selected:(selecteId? true : false)},{
            where:{
                user_id:user_id
            }
        })
    }
    async selectUnCarts(user_id){
        return await Cart.update({selected:false},{
            where:{
                user_id:user_id
            }
        })
    }
}


module.exports = new cartService()